package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;

/**
 * Title  : 538. Convert BST to Greater Tree
 * Source : https://leetcode.cn/problems/convert-bst-to-greater-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-24
 */

public class LeetCode_538 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int dfs(TreeNode root) {
        if (root != null) {
            return root.val + dfs(root.left) + dfs(root.right);
        }
        return 0;
    }


    public TreeNode convertBST(TreeNode root) {
        int sum = dfs(root);
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        TreeNode current = root;
        while (current != null || !sta.isEmpty()) {
            if (current != null) {
                sta.push(current);
                current = current.left;
            } else {
                current = sta.pop();
                int val = current.val;
                current.val = sum;
                sum -= val;
                current = current.right;
            }
        }
        return root;
    }
}
